package cn.com.twoke.app.pin_dou_dou.color;

import cn.com.twoke.app.pin_dou_dou.utils.ColorLabUtils;

import java.awt.*;

/**
 * 计算 CMC 色差（常用于纺织行业）
 */
public class CIE_CMC implements ColorDifferenceCalculator{

    @Override
    public double deltaE(Color color1, Color color2) {
        double[] lab1 = ColorLabUtils.rgbToLab(color1);
        double[] lab2 = ColorLabUtils.rgbToLab(color2);

        double dl = lab1[0] - lab2[0];
        double da = lab1[1] - lab2[1];
        double db = lab1[2] - lab2[2];

        double c1 = Math.sqrt(lab1[1] * lab1[1] + lab1[2] * lab1[2]);
        double c2 = Math.sqrt(lab2[1] * lab2[1] + lab2[2] * lab2[2]);
        double dc = c1 - c2;

        double dh = Math.sqrt(da * da + db * db - dc * dc);

        // CMC 参数（通常 l:c = 2:1）
        double l = 2.0;
        double c = 1.0;

        double sl = (lab1[0] < 16) ? 0.511 : (0.040975 * lab1[0]) / (1 + 0.01765 * lab1[0]);
        double sc = (0.0638 * c1) / (1 + 0.0131 * c1) + 0.638;
        double f = Math.sqrt(Math.pow(c1, 4) / (Math.pow(c1, 4) + 1900));

        double t = (lab1[1] >= 0) ?
                0.56 + Math.abs(0.2 * Math.cos(Math.toRadians(lab1[2] + 168))) :
                0.36 + Math.abs(0.4 * Math.cos(Math.toRadians(lab1[2] + 35)));

        double sh = sc * (f * t + 1 - f);

        return Math.sqrt(
                Math.pow(dl / (l * sl), 2) +
                        Math.pow(dc / (c * sc), 2) +
                        Math.pow(dh / sh, 2)
        );
    }

}
